import { triplitClient } from "@main/triplit/client";
import type {
  CreateMcpToolData,
  McpTool,
  UpdateMcpToolData,
} from "@shared/triplit/types";
import { injectable } from "inversify";
import { BaseDbService } from "./base-db-service";

@injectable()
export class McpToolDbService extends BaseDbService {
  constructor() {
    super("mcpTools");
  }

  async insertMcpTool(data: CreateMcpToolData): Promise<McpTool> {
    return await triplitClient.insert("mcpTools", {
      ...data,
      enabled: data.enabled ?? true,
    });
  }

  async updateMcpTool(
    toolId: string,
    updateData: UpdateMcpToolData,
  ): Promise<void> {
    await triplitClient.update("mcpTools", toolId, async (tool) => {
      Object.assign(tool, updateData, {
        updatedAt: new Date(),
      });
    });
  }

  async deleteMcpTool(toolId: string): Promise<void> {
    await triplitClient.delete("mcpTools", toolId);
  }

  async getMcpToolById(toolId: string): Promise<McpTool | null> {
    return await triplitClient.fetchById("mcpTools", toolId);
  }

  async getMcpToolsByServerId(serverId: string): Promise<McpTool[]> {
    const query = triplitClient
      .query("mcpTools")
      .Where("mcpServerId", "=", serverId);

    return await triplitClient.fetch(query);
  }

  async getEnabledMcpToolsByServerId(serverId: string): Promise<McpTool[]> {
    const query = triplitClient
      .query("mcpTools")
      .Where("mcpServerId", "=", serverId)
      .Where("enabled", "=", true);

    return await triplitClient.fetch(query);
  }

  async enableMcpTool(toolId: string, enabled: boolean): Promise<void> {
    await this.updateMcpTool(toolId, { enabled });
  }

  async clearMcpTools(serverId: string): Promise<void> {
    const query = triplitClient
      .query("mcpTools")
      .Where("mcpServerId", "=", serverId);

    const tools = await triplitClient.fetch(query);

    await triplitClient.transact(async (tx) => {
      const deletePromises = tools.map((tool) =>
        tx.delete("mcpTools", tool.id),
      );

      await Promise.all(deletePromises);
    });
  }
}
